package com.icode.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.icode.common.exception.NoStockException;
import com.icode.common.to.OrderTo;
import com.icode.common.utils.R;
import com.icode.common.vo.MemberResponseVo;
import com.icode.gulimall.order.interceptor.OrderInterceptor;
import com.icode.gulimall.order.entity.OrderItemEntity;
import com.icode.gulimall.order.enums.OrderStatusEnum;
import com.icode.gulimall.order.feign.CartFeignService;
import com.icode.gulimall.order.feign.MemberFeignService;
import com.icode.gulimall.order.feign.ProductFeignService;
import com.icode.gulimall.order.feign.WareFeignService;
import com.icode.gulimall.order.service.OrderItemService;
import com.icode.gulimall.order.to.OrderCreateTo;
import com.icode.gulimall.order.vo.SpuInfoVo;
import com.icode.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icode.common.utils.PageUtils;
import com.icode.common.utils.Query;

import com.icode.gulimall.order.dao.OrderDao;
import com.icode.gulimall.order.entity.OrderEntity;
import com.icode.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


import static com.icode.common.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;


    @Autowired
    ThreadPoolExecutor executor;

    private ThreadLocal<OrderSubmitVo> confirmSubmitVo = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponseVo responseVo = OrderInterceptor.loginUser.get();
        //设置订单令牌
        String orderToken = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(USER_ORDER_TOKEN_PREFIX + responseVo.getId(), orderToken);
        orderConfirmVo.setOrderToken(orderToken);

        //设置会员积分信息
        orderConfirmVo.setIntegration(responseVo.getIntegration());

        //获取请求上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> memberTask = CompletableFuture
                .runAsync(() -> {
                    //添加到异步请求的上下文中
                    RequestContextHolder.setRequestAttributes(requestAttributes);

                    //远程调用在线用户的收货地址信息，并封装
                    R r = memberFeignService.listInfo(responseVo.getId());
                    if (r.getCode() == 0) {
                        List<MemberAddressVo> memberAddressVos = r.getData(new TypeReference<List<MemberAddressVo>>() {
                        });
                        orderConfirmVo.setMemberAddressVos(memberAddressVos);
                    }
                }, executor);
        CompletableFuture<Void> cartAndWareTask = CompletableFuture
                .runAsync(() -> {
                    //添加到异步请求的上下文中
                    RequestContextHolder.setRequestAttributes(requestAttributes);

                    //从redis中获取购物车中所有选中的商品
                    R checkedItems = cartFeignService.getCheckedItems();
                    if (checkedItems.getCode() == 0) {
                        List<OrderItemVo> itemVoList = checkedItems.getData(new TypeReference<List<OrderItemVo>>() {
                        });
                        orderConfirmVo.setItems(itemVoList);
                    }
                }, executor)
                .thenRunAsync(() -> {
                    //添加到异步请求的上下文中
                    RequestContextHolder.setRequestAttributes(requestAttributes);

                    //判断商品库存信息
                    Map<String, Integer> checkInfo = orderConfirmVo.getItems().stream().collect(Collectors.toMap(item -> String.valueOf(item.getSkuId()), item -> item.getCount()));
                    R checkItemsStock = wareFeignService.checkItemsStock(checkInfo);
                    if (checkItemsStock.getCode() == 0) {
                        Map<Long, Boolean> stockData = checkItemsStock.getData(new TypeReference<Map<Long, Boolean>>() {
                        });
                        orderConfirmVo.setStocks(stockData);
                    }
                }, executor);

        //等待异步线程执行完毕
        CompletableFuture.allOf(memberTask, cartAndWareTask).get();

        return orderConfirmVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderResponseVo orderSubmit(OrderSubmitVo submitVo) {

        confirmSubmitVo.set(submitVo);

        SubmitOrderResponseVo submitOrderResponseVo = new SubmitOrderResponseVo();
        MemberResponseVo responseVo = OrderInterceptor.loginUser.get();

        //1、验证令牌是否合法【令牌的对比和删除必须保证原子性】
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        String orderToken_web = submitVo.getOrderToken();

        //通过lure脚本原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(USER_ORDER_TOKEN_PREFIX + responseVo.getId()),
                orderToken_web);

        if (result == 0l) {
            //令牌验证失败
            submitOrderResponseVo.setCode(1);
            return submitOrderResponseVo;
        } else {
            //令牌验证成功
            OrderCreateTo createTo = createOrder();
            //2、验证价格
            BigDecimal payAmount = createTo.getOrder().getPayAmount();
            BigDecimal payPrice = submitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                saveOrder(createTo);
                //重新加载购物车的信息
                R checkedItems = cartFeignService.getCheckedItems();
                if (checkedItems.getCode() == 0) {
                    List<OrderItemVo> itemsData = checkedItems.getData(new TypeReference<List<OrderItemVo>>() {
                    });

                    //需要扣减库存的商品和商品数量
                    //假设目前商品都在一个厂库1 todo 丰富仓储系统
                    WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();

                    Long addrId = submitVo.getAddrId();
                    R addressInfo = memberFeignService.addressInfo(addrId);
                    MemberAddressVo addressVo = addressInfo.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
                    });
                    wareSkuLockVo.setMemberAddressVo(addressVo);
                    wareSkuLockVo.setLocks(itemsData);
                    wareSkuLockVo.setOrderSn(createTo.getOrder().getOrderSn());

                    //远程调用异常，由于事务是order服务的，它不会传播到Feign调用的请求中，让库存回滚，
                    //所以引入RabbiMq实现数据的最终一致性，（自动补回扣减的库存）
                    R isDec = wareFeignService.lockItemsStock(wareSkuLockVo);
                    if (isDec.getCode() == 0) {
                        //订单库存扣减成功
                        submitOrderResponseVo.setOrder(createTo.getOrder());
                        //TODO 订单创建成功，发送消息给MQ
                        rabbitTemplate.convertAndSend("order-event-exchange", "order.create", createTo.getOrder());

                        //删除用户购物车
                        //redisTemplate.delete(CART_PREFIX + responseVo.getId());
                        submitOrderResponseVo.setCode(0);
                        return submitOrderResponseVo;
                    } else {
                        //订单库存扣减失败
                        String msg = (String) isDec.get("msg");
                        throw new NoStockException(msg);
                    }
                }
            }
            //价格差异大
            submitOrderResponseVo.setCode(2);
            return submitOrderResponseVo;
        }
    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();

        //1.生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = orderBuilder(orderSn);
        createTo.setOrder(orderEntity);

        List<OrderItemEntity> orderItemVos = orderItemsBuilder(orderSn);
        //3、验价(计算价格、积分等信息)
        computePrice(orderEntity, orderItemVos);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItemVos);

        return createTo;
    }

    /**
     * 构造订单-基本信息（用户、收货地址、自动确认时间）
     *
     * @param orderSn
     * @return
     */
    private OrderEntity orderBuilder(String orderSn) {
        OrderSubmitVo submitVo = confirmSubmitVo.get();
        MemberResponseVo responseVo = OrderInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setPayType(submitVo.getPayType());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(responseVo.getId());
        orderEntity.setMemberUsername(responseVo.getUsername());

        //封装运费
        FareVo fare = getFare(submitVo.getAddrId());
        orderEntity.setFreightAmount(fare.getFare());

        //添加地址信息
        R info = memberFeignService.addressInfo(submitVo.getAddrId());
        if (info.getCode() == 0) {
            MemberAddressVo infoData = info.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
            });
            orderEntity.receiveDate(orderEntity,
                    infoData.getName(),
                    infoData.getPhone(),
                    infoData.getPostCode(),
                    infoData.getCity(),
                    infoData.getProvince(),
                    infoData.getRegion(),
                    infoData.getDetailAddress());
        }
        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

    /**
     * 构造订单项
     *
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> orderItemsBuilder(String orderSn) {
        //远程调用获取购物车选中的商品
        R checkedItems = cartFeignService.getCheckedItems();
        if (checkedItems.getCode() == 0) {
            List<OrderItemVo> itemsData = checkedItems.getData(new TypeReference<List<OrderItemVo>>() {
            });
            List<OrderItemEntity> collect = itemsData.stream().map(orderItemVo -> {
                OrderItemEntity orderItemEntity = orderItemBuilder(orderItemVo);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 构造单个商品的订单项并保存
     *
     * @param orderItemVo
     * @return
     */
    private OrderItemEntity orderItemBuilder(OrderItemVo orderItemVo) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //spu信息
        Long skuId = orderItemVo.getSkuId();
        R skuInfo = productFeignService.getInfoBySkuId(skuId);
        if (skuInfo.getCode() == 0) {
            SpuInfoVo spuInfoVo = skuInfo.getData(new TypeReference<SpuInfoVo>() {
            });
            orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
            orderItemEntity.setSpuBrand(spuInfoVo.getBrandName());
            orderItemEntity.setSpuId(spuInfoVo.getId());
            orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        }
        //sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());
        orderItemEntity.setSkuPic(orderItemVo.getImage());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //4、商品的积分信息 todo 远程掉用coupon服务查询商品积分情况
        orderItemEntity.setGiftGrowth(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount())).intValue());
        orderItemEntity.setGiftIntegration(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount())).intValue());

        //5、订单项的价格信息 商品折扣分解金额 默认值：0
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额. 总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }


    /**
     * 计算价格的方法
     *
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {

        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值 默认为 0
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        BigDecimal freightAmount = orderEntity.getFreightAmount();
        orderEntity.setPayAmount(total.add(freightAmount));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }


    /**
     * 获取运费
     *
     * @param addrId
     * @return
     */
    @Override
    public FareVo getFare(Long addrId) {
        //远程调用获取运费 参考相关阿里云API，此处暂时默认返会
        R fare = wareFeignService.getFare(addrId);
        if (fare.getCode() == 0) {
            FareVo fareData = fare.getData(new TypeReference<FareVo>() {
            });
            return fareData;
        }
        // todo 运费异常处理 暂时返回空对象
        return new FareVo();
    }

    /**
     * 通过订单号获取订单
     *
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderInfoByOrderSn(String orderSn) {
        OrderEntity entity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return entity;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {

        //关闭订单之前先查询一下数据库，判断此订单状态是否已支付
        OrderEntity orderInfo = this.getOne(new QueryWrapper<OrderEntity>().
                eq("order_sn", orderEntity.getOrderSn()));

        if (orderInfo.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {

            //代付款状态进行关单
            OrderEntity orderUpdate = new OrderEntity();
            orderUpdate.setId(orderInfo.getId());
            orderUpdate.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(orderUpdate);

            // 发送消息给MQ
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderInfo, orderTo);

            try {
                //TODO 确保每个消息发送成功，给每个消息做好日志记录，(给数据库保存每一个详细信息)保存每个消息的详细信息
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //TODO 定期扫描数据库，重新发送失败的消息
            }
        }

    }

    private void saveOrder(OrderCreateTo createTo) {
        OrderEntity order = createTo.getOrder();
        Date now = new Date();
        order.setModifyTime(now);
        order.setCreateTime(now);
        this.save(order);
        Long id = order.getId();//获取订单的Id
        List<OrderItemEntity> orderItems = createTo.getOrderItems();
        orderItems.stream().forEach(item -> item.setOrderId(id));
        orderItemService.saveBatch(orderItems);
    }

}